package cn.seaboot.admin.logger.service;

import cn.seaboot.admin.logger.bean.AccessLog;
import cn.seaboot.admin.logger.dao.AccessLogDao;
import cn.seaboot.admin.quartz.service.ScheduleJobService;
import cn.seaboot.admin.user.context.UserContext;
import cn.seaboot.commons.core.Snowflake;
import cn.seaboot.commons.core.SnowflakeFactory;
import cn.seaboot.commons.core.StringUtils;
import cn.seaboot.commons.eventbus.EventbusListener;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Service
 * 日志表 t_sys_log_access
 * <p>
 *
 * @author Mr.css on 2018-6-20
 */
@Service
@EventbusListener
public class AccessLogService {
    private Snowflake snowflake = SnowflakeFactory.createSnowflake();


    @Resource
    private AccessLogDao accessDao;

    @Resource
    private UserContext userContext;


    @Resource
    private ScheduleJobService scheduleJobService;

    @PostConstruct
    public void init() throws SchedulerException {
        scheduleJobService.builder()
                .withEager(true)
                .withGroup("clean-data")
                .withName("t_sys_log_access")
                .withCron("0 0 23 L * ?")
                .withDescription("Regular log cleaning tasks.")
                .withRunnable(this::deletePreMonthData)
                .build();
    }

    /**
     * 保存日志
     *
     * @param log 访问日志
     * @return 受影响行数
     */
    public int saveLog(AccessLog log) {
        log.setId(snowflake.nextStrId());
        log.setOrgId(userContext.getOrgId());
        log.setUserId(userContext.getUserId());
        log.setDeptId(userContext.getUserDeptId());
        log.setUserName(userContext.getUser().getUsername());

        // 数据截断，避免字段过长
        log.setOperation(StringUtils.truncateTail(log.getOperation(), 64));
        log.setServletPath(StringUtils.truncateTail(log.getServletPath(), 128));

        log.setRequestBody(StringUtils.truncateTail(log.getRequestBody(), 65535));
        log.setResponseBody(StringUtils.truncateTail(log.getResponseBody(), 65535));
        return accessDao.insert(log);
    }

    /**
     * 查询列表
     *
     * @param params -
     * @return -
     */
    public List<AccessLog> queryList(Map<String, Object> params) {
        return accessDao.selectList(params);
    }

    /**
     * 清理一个月之前的日志
     *
     * @return 受影响行数
     */
    public int deletePreMonthData() {
        return accessDao.deletePreMonthData();
    }
}
